﻿using UnityEngine;
using System.Collections;
//using System;
public class Timer_yang : MonoBehaviour {
	//一个计时器小工具，调用它的静态方法createTimer来生成一个计时器//
	public class timerEventArgs : System.EventArgs{
		private float _second;
		public timerEventArgs(float now){
			_second = now;
		}
		public float second { get{return _second;}}
	}
	public delegate void Tick(GameObject obj,timerEventArgs args);
	public Tick tickEvent;
	public Tick thenEvent;
	private bool isLoop;
	private int timeSpan;
	private float now,tick;
    public float Now { get { return now; } }
    public float RestTime { get { return timeSpan - now; } }
    private bool sw = false;
	public bool isRun = false;

	public static Timer_yang createTimer(bool loop = false,string name = "Timer",int span = 1){
		//生成一个计时器,参数:(定时器名,触发间隔,是否循环)//
        GameObject timerContent = GameObject.Find("myTimers");
        if (!timerContent)
            timerContent =  new GameObject("myTimers");
		//Debuger.Log ("计时器"+name+"被创建");
		GameObject timer = new GameObject(name);
        timer.transform.parent = timerContent.transform;
		Timer_yang initTimer = timer.AddComponent<Timer_yang>();
        initTimer.isLoop = loop;
        initTimer.timeSpan = span;
        initTimer.now = 0;
        initTimer.tick = 0;
        return initTimer;
	}
	// Update is called once per frame
	void Update () {
		if(sw){
			now += Time.deltaTime;
            tick += Time.deltaTime;
			if(now >= timeSpan){
				//Debuger.Log("计时器触发！间隔："+timeSpan+"秒");
				if(isLoop){
                    if(thenEvent!=null)
                        thenEvent(this.gameObject,new timerEventArgs(now));
					now = 0;
				}
				else{
                    if (thenEvent != null)
                        thenEvent(this.gameObject, new timerEventArgs(now));
					Destroy(this.gameObject);
				}
			}
			else if(tick>=1){
                if(tickEvent!=null)
                    tickEvent(this.gameObject,new timerEventArgs(now));
                tick = 0;
			}
		}
	}
	public void start(){
		//Debuger.Log ("计时器"+this.gameObject.name+"开始运行！");
		sw = true;
		isRun = true;
	}
	public void reset(){
		now = 0;
	}
	public void stop(){
		Debug.Log ("计时器"+this.gameObject.name+"停止！");
		sw = false;
		isRun = false;
	}
    public void changeSpan(int newSpan) {
        timeSpan = newSpan;
    }
	public void destroy(){
		tickEvent = null;
		isRun = false;
        Destroy(this.gameObject);
 	}
}
